import { ref, computed } from 'vue';
import { defineStore } from 'pinia';

//创建一个简单的 Store 学会定义 State、Getters 和 Actions。 选项式
export const useStoreOne = defineStore('counterone', {
  //写法1
  state: () => ({
    count: 0,
    name: 'Bob',
    isAdmin: true,
    items: [] as string[],
    hasChanged: true,
  }),
  //写法2
  // state: () => {
  //   return {
  //     count: 0,
  //     name: 'Bob',
  //     isAdmin: true,
  //     items: [] as string[],
  //     hasChanged: true,
  //   };
  // },
  getters: {
    doubleCount: (state) => state.count * 2,
    doublePlusone: (state) => state.count * 2 + 1,
    // doublePlusone(): number {
    //   return this.doubleCount + 1; // 正常访问
    // },
  },
  actions: {
    increment() {
      this.count++;
    },
    //$reset重置演示
    reset() {
      this.$reset(); //重置
    },
  },
  //自定义配置数据持久化
  persist: {
    key: 'user',
    storage: localStorage,
    pick: ['count'],
    serializer: {
      serialize: (value: unknown) => btoa(JSON.stringify(value)), //base64编码
      deserialize: (value: string) => JSON.parse(atob(value)), //base64解码
    },
  },
  //打开数据持久化
  // persist: true,
});

//创建一个简单的 Store 学会定义 State、Getters 和 Actions。 组合式
export const useStoretwo = defineStore(
  'countertwo',
  () => {
    //等同于的选项式state
    const count = ref(0);
    const name = ref('Bob');
    const isAdmin = ref(true);
    //等同于选项式的getters，需要使用computed
    const doubleCount = computed(() => count.value * 2);
    const doublePlusone = computed(() => {
      return doubleCount.value + 1;
    });
    //等同于选项式的actions
    const increment = () => {
      count.value++;
    };
    //重置方法
    const reset = () => {
      count.value = 0;
      name.value = 'Bob';
      isAdmin.value = true;
    };
    return { count, name, isAdmin, doubleCount, doublePlusone, increment, reset };
  },
  {
    //自定义配置数据持久化
    persist: {
      key: 'users',
      storage: localStorage,
      pick: ['name'],
      serializer: {
        serialize: (value:unknown) => btoa(JSON.stringify(value)), //base64编码
        deserialize: (value: string) => JSON.parse(atob(value)), //base64解码
      },
    },
    //打开数据持久化
    // persist:true
  },
);
